﻿using System;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using SelfService.Model;
using SelfService.Model.Models;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using WalkingTec.Mvvm.Mvc;
using SelfService.ViewModel.SysConfigGroupVMs;


namespace SelfService.Controllers
{
    
    [AuthorizeJwtWithCookie]
    [ActionDescription("配置分组")]
    [ApiController]
    [Route("api/SysConfigGroup")]
	public partial class SysConfigGroupController : BaseApiController
    {
        [ActionDescription("Sys.Search")]
        [HttpPost("Search")]
		public IActionResult Search(SysConfigGroupSearcher searcher)
        {
            if (ModelState.IsValid)
            {
                var vm = Wtm.CreateVM<SysConfigGroupListVm>();
                vm.Searcher = searcher;
                return Content(vm.GetJson(enumToString: false));
            }
            else
            {
                return BadRequest(ModelState.GetErrorJson());
            }
        }

        [ActionDescription("获取配置列表")]
        [Public]
        [HttpGet("List")]
        public async Task<IActionResult> List()
        {
            try
            {
                var groupList = await DC.Set<SysConfigGroup>().ToListAsync();
                IDictionary<string, object> config = new ExpandoObject();
                foreach (var group in groupList)
                {
                    var list = await DC.Set<SysConfig>().Where(e => e.GroupId == group.ID).ToListAsync();
                    IDictionary<string, object> item = new ExpandoObject();
                    foreach (var element in list)
                    {
                        if (element.ValueType == SysConfigValueTypeEnum.文件)
                        {
                            item.Add(element.Key, $"/api/_file/GetFile/{element.Value}");
                        }
                        else
                        {
                            item.Add(element.Key, element.Value);
                        }
                    }
                    config.Add(group.Key, item);
                }
                return Content(JsonConvert.SerializeObject(config), "application/json");
            }
            catch (Exception e)
            {
                Wtm.DoLog(JsonConvert.SerializeObject(e), ActionLogTypesEnum.Exception, "SysConfigGroup", "List");
                ModelState.AddModelError(" ", "获取配置失败");
                return BadRequest(ModelState.GetErrorJson());
            }
        }

        [ActionDescription("Sys.Get")]
        [HttpGet("{id}")]
        public SysConfigGroupVm Get(string id)
        {
            var vm = Wtm.CreateVM<SysConfigGroupVm>(id);
            return vm;
        }

        [ActionDescription("Sys.Create")]
        [HttpPost("Add")]
        public IActionResult Add(SysConfigGroupVm vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                vm.DoAdd();
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }

        }

        [ActionDescription("Sys.Edit")]
        [HttpPut("Edit")]
        public IActionResult Edit(SysConfigGroupVm vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                vm.DoEdit(false);
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }
        }

		[HttpPost("BatchDelete")]
        [ActionDescription("Sys.Delete")]
        public IActionResult BatchDelete(string[] ids)
        {
            var vm = Wtm.CreateVM<SysConfigGroupBatchVm>();
            if (ids != null && ids.Count() > 0)
            {
                vm.Ids = ids;
            }
            else
            {
                return Ok();
            }
            if (!ModelState.IsValid || !vm.DoBatchDelete())
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                return Ok(ids.Count());
            }
        }


        [ActionDescription("Sys.Export")]
        [HttpPost("ExportExcel")]
        public IActionResult ExportExcel(SysConfigGroupSearcher searcher)
        {
            var vm = Wtm.CreateVM<SysConfigGroupListVm>();
            vm.Searcher = searcher;
            vm.SearcherMode = ListVMSearchModeEnum.Export;
            return vm.GetExportData();
        }

        [ActionDescription("Sys.CheckExport")]
        [HttpPost("ExportExcelByIds")]
        public IActionResult ExportExcelByIds(string[] ids)
        {
            var vm = Wtm.CreateVM<SysConfigGroupListVm>();
            if (ids != null && ids.Count() > 0)
            {
                vm.Ids = new List<string>(ids);
                vm.SearcherMode = ListVMSearchModeEnum.CheckExport;
            }
            return vm.GetExportData();
        }

        [ActionDescription("Sys.DownloadTemplate")]
        [HttpGet("GetExcelTemplate")]
        public IActionResult GetExcelTemplate()
        {
            var vm = Wtm.CreateVM<SysConfigGroupImportVm>();
            var qs = new Dictionary<string, string>();
            foreach (var item in Request.Query.Keys)
            {
                qs.Add(item, Request.Query[item]);
            }
            vm.SetParms(qs);
            var data = vm.GenerateTemplate(out string fileName);
            return File(data, "application/vnd.ms-excel", fileName);
        }

        [ActionDescription("Sys.Import")]
        [HttpPost("Import")]
        public ActionResult Import(SysConfigGroupImportVm vm)
        {
            if (vm!=null && (vm.ErrorListVM.EntityList.Count > 0 || !vm.BatchSaveData()))
            {
                return BadRequest(vm.GetErrorJson());
            }
            else
            {
                return Ok(vm?.EntityList?.Count ?? 0);
            }
        }


    }
}
